package com.snda.sng.chat
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	/**
	 * ChatConnection
	 * @author 任冬 rending01@snda.com
	 * $Id: ChatConnection.as 26 2011-07-21 02:37:23Z rendong $
	 * @version 1.0
	 */
	public class ChatConnection extends Socket
	{
		/**
		 * 包处理函数，参数为 type:short, len:int, msg:ByteArray
		 */		
		private var packHandler:Function;
		
		/**
		 * 客户端包缓冲 
		 */		
		private var buffer:ByteArray;
		
		/**
		 * 初始化 
		 * @param packHandler
		 * 
		 */		
		public function ChatConnection(packHandler:Function)
		{
			super();
			
			// 设置字节序为主机字节序
			this.endian = Endian.LITTLE_ENDIAN;
			
			this.packHandler = packHandler;
			
			addEventListener(ProgressEvent.SOCKET_DATA, dataHandler);
		}
		
		// 处理数据
		private function dataHandler(e:ProgressEvent):void
		{
			if (buffer == null){
				buffer = new ByteArray();
				buffer.endian = Endian.LITTLE_ENDIAN;
			}
			
			readBytes(buffer, buffer.position, bytesAvailable);
			buffer.position = buffer.length;
			
			var oldpos:int = buffer.position;
			var len:int=0,type:int=0;
			var message:ByteArray, tmp:ByteArray;
			
			
			buffer.position = 0;
			if (oldpos > 4)
				len = buffer.readInt(); // 读取长度
			
			while(len > 0 && buffer.length >= (len +4))
			{
				type = buffer.readShort();
				message = new ByteArray();
				message.endian = Endian.LITTLE_ENDIAN;
				buffer.readBytes(message, 0, len -2);
				
				packHandler(type, len, message);
				
				message.clear();// 释放
				
				// 拷贝剩下的到buffer中
				if (buffer.bytesAvailable > 0)
				{
					tmp = new ByteArray();
					tmp.endian = Endian.LITTLE_ENDIAN;
					buffer.readBytes(tmp,0, 0);
					oldpos = tmp.length;
				}else{
					tmp = null;
				}
				
				buffer.clear();
				buffer = tmp;
				
				if (buffer != null){
					buffer.position = 0;
					if (oldpos > 4)
						len = buffer.readInt(); // 读取长度
					else
						len = 0;
				}else{
					len = 0;
				}
			}
			
			if (buffer != null)
				buffer.position = oldpos;
			
		}
	}
}
